"""
肺结节CT场景API接口
"""

from fastapi import APIRouter, HTTPException
from typing import Optional, List
from pydantic import BaseModel

from medical_scenes.scenes.lung_nodule.processor import LungNoduleProcessor
from medical_scenes.scenes.lung_nodule.models import (
    LungNoduleProcessingResult,
    NoduleDetectionTask,
    NoduleSegmentationTask,
    NoduleClassificationTask
)

# 创建路由
router = APIRouter(prefix="/api/medical-scenes/lung-nodule", tags=["lung-nodule"])

# 初始化处理器
processor = LungNoduleProcessor()

class TaskExecutionRequest(BaseModel):
    """任务执行请求"""
    image_data: str
    sensitivity: Optional[float] = 0.5
    nodule_ids: Optional[List[str]] = None

@router.get("/tasks", response_model=List[dict])
async def list_tasks():
    """
    获取肺结节场景下的所有任务列表
    
    Returns:
        List[dict]: 任务列表
    """
    try:
        tasks = processor.get_tasks()
        return tasks
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list tasks: {str(e)}")

@router.post("/tasks/detection/execute", response_model=LungNoduleProcessingResult)
async def execute_detection_task(request: TaskExecutionRequest):
    """
    执行肺结节检测任务
    
    Args:
        request: 任务执行请求
        
    Returns:
        LungNoduleProcessingResult: 处理结果
    """
    try:
        if not processor.validate_input(request.image_data):
            raise HTTPException(status_code=400, detail="Invalid CT image data")
        
        result = processor.detect_nodules(
            request.image_data, 
            sensitivity=request.sensitivity
        )
        
        return LungNoduleProcessingResult(detections=result)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Detection failed: {str(e)}")

@router.post("/tasks/segmentation/execute", response_model=LungNoduleProcessingResult)
async def execute_segmentation_task(request: TaskExecutionRequest):
    """
    执行肺结节分割任务
    
    Args:
        request: 任务执行请求
        
    Returns:
        LungNoduleProcessingResult: 处理结果
    """
    try:
        if not processor.validate_input(request.image_data):
            raise HTTPException(status_code=400, detail="Invalid CT image data")
        
        result = processor.segment_nodules(
            request.image_data, 
            nodule_ids=request.nodule_ids
        )
        
        return LungNoduleProcessingResult(segmentations=result)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Segmentation failed: {str(e)}")

@router.post("/tasks/classification/execute", response_model=LungNoduleProcessingResult)
async def execute_classification_task(request: TaskExecutionRequest):
    """
    执行肺结节良恶性分类任务
    
    Args:
        request: 任务执行请求
        
    Returns:
        LungNoduleProcessingResult: 处理结果
    """
    try:
        if not processor.validate_input(request.image_data):
            raise HTTPException(status_code=400, detail="Invalid CT image data")
        
        result = processor.classify_nodules(
            request.image_data, 
            nodule_ids=request.nodule_ids
        )
        
        return LungNoduleProcessingResult(classifications=result)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Classification failed: {str(e)}")

@router.post("/process", response_model=LungNoduleProcessingResult)
async def process_lung_nodule(
    image_data: str, 
    task_id: Optional[str] = None,
    sensitivity: float = 0.5,
    nodule_ids: Optional[List[str]] = None
):
    """
    处理肺结节CT图像（向后兼容的统一接口）
    
    Args:
        image_data: 图像数据
        task_id: 任务ID（detection, segmentation, classification），如果为None则执行所有任务
        sensitivity: 检测敏感度
        nodule_ids: 结节ID列表
        
    Returns:
        LungNoduleProcessingResult: 处理结果
    """
    try:
        if not processor.validate_input(image_data):
            raise HTTPException(status_code=400, detail="Invalid CT image data")
        
        result = processor.process(
            image_data, 
            task_id=task_id,
            sensitivity=sensitivity,
            nodule_ids=nodule_ids
        )
        
        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
